package com.lzy.api.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Slf4j
@Aspect
public class ServiceLogAspect {

    @Around("execution(* com.lzy.service.impl..*.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取方法名
        String pointName = joinPoint.getTarget().getClass().getName()
                + "."
                + joinPoint.getSignature().getName();

        StopWatch stopWatch = new StopWatch();

        // 需要统计每一个Service实现的执行时间，如果执行的时间太久，则进行error级别的日志输出
        stopWatch.start("执行主业务" + pointName);
        Object proceed =  joinPoint.proceed(); //在环绕通知中调用proceed方法,执行原方法
        stopWatch.stop();

        log.info(stopWatch.prettyPrint());
        log.info("任务总数:" + stopWatch.getTaskCount());
        log.info("执行任务总时间:" + stopWatch.getTotalTimeMillis() + "ms");

        long takeTimes = stopWatch.getTotalTimeMillis();
        if(takeTimes > 3000){
            log.error("{} 执行时间太长了，耗费了 {} 毫秒", pointName, takeTimes);
        }else if(takeTimes > 2000){
            log.warn("{} 执行时间有点久，耗费了 {} 毫秒", pointName, takeTimes);
        }else{
            log.info("{} 执行时间正常，耗费了 {} 毫秒", pointName, takeTimes);
        }
        return proceed;
    }
}


